package com.janko.springbootbase.juc.completableFuture;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;

/**
 * @Author nyk
 * @Date 2022/4/14 10:00
 * @Version 1.0
 * @Desc 测试CompletableFuture例子
 */
@Slf4j
public class Demo3Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        long start = System.currentTimeMillis();
//
//        getFuturesList();
//
//        long end= System.currentTimeMillis();
//        System.out.println(String.format(Thread.currentThread().getName()+"该方法执行共耗时了%d",end-start));

        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            int finalI = i;
            futures.add(CompletableFuture.supplyAsync(() -> getSomeThing(finalI)));
        }
        //等待全部完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        //获取内容
        for (CompletableFuture<String> future : futures) {
            try {
                String s = future.get();
                System.out.println(s);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    public static  String getSomeThing(int i){
        return "这是参数" + i;
    }


    // 使用CompletableFuture集合，利用join方式去执行多个并发任务
    private static void getFuturesList() {
        List<CompletableFuture> futures = new ArrayList();
        for (Integer adCode : getUserIdList()) {
            futures.add(CompletableFuture.runAsync(() -> print(adCode)));
        }
        CompletableFuture<Void> getUserInfo = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
        getUserInfo.thenAccept(new Consumer<Void>() {
            @Override
            public void accept(Void aVoid) {
                System.out.println(String.format("%d方法执行结束", Thread.currentThread().getName()));
            }
        });
        getUserInfo.join();
    }

    public static void print(Integer uid) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(Thread.currentThread() + "\t" + uid);
    }

    // 获取用户集合
    public static List<Integer> getUserIdList() {
        return Arrays.asList(12, 3, 4, 5, 6, 7, 8, 9, 10);
    }
}
